<template>
  <div class="goals-container">
    <!-- 目标概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="current-goal-card">
          <template #header>
            <div class="card-header">
              <span>当前目标</span>
              <el-button type="primary" @click="showGoalForm">
                {{ currentGoal ? '修改目标' : '设置目标' }}
              </el-button>
            </div>
          </template>
          
          <div v-if="currentGoal" class="goal-overview">
            <div class="goal-type">
              <el-tag :type="getGoalType(currentGoal.type)" size="large">
                {{ getGoalText(currentGoal.type) }}
              </el-tag>
            </div>
            
            <el-descriptions :column="3" border>
              <el-descriptions-item label="目标体重">
                {{ currentGoal.targetWeight }}kg
              </el-descriptions-item>
              <el-descriptions-item label="每周目标">
                {{ getWeeklyGoalText(currentGoal.weeklyGoal) }}
              </el-descriptions-item>
              <el-descriptions-item label="目标日期">
                {{ formatDate(currentGoal.targetDate) }}
              </el-descriptions-item>
              <el-descriptions-item label="每日热量">
                {{ currentGoal.dailyCalories }}kcal
              </el-descriptions-item>
              <el-descriptions-item label="蛋白质">
                {{ currentGoal.protein }}g
              </el-descriptions-item>
              <el-descriptions-item label="碳水化合物">
                {{ currentGoal.carbs }}g
              </el-descriptions-item>
            </el-descriptions>

            <div class="goal-progress">
              <h4>目标进度</h4>
              <el-progress
                :percentage="goalProgress"
                :status="goalProgress >= 100 ? 'success' : ''"
                :stroke-width="20"
              >
                <template #default="{ percentage }">
                  <span class="progress-label">
                    {{ percentage.toFixed(1) }}%
                  </span>
                </template>
              </el-progress>
            </div>
          </div>
          
          <el-empty
            v-else
            description="暂未设置目标"
          >
            <el-button type="primary" @click="showGoalForm">
              立即设置
            </el-button>
          </el-empty>
        </el-card>
      </el-col>
    </el-row>

    <!-- 目标进展图表 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>体重变化趋势</span>
              <el-select v-model="weightChartRange" size="small">
                <el-option label="最近一周" value="week" />
                <el-option label="最近一月" value="month" />
                <el-option label="最近三月" value="quarter" />
              </el-select>
            </div>
          </template>
          <div ref="weightChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>营养摄入达标率</span>
              <el-select v-model="nutritionChartRange" size="small">
                <el-option label="最近一周" value="week" />
                <el-option label="最近一月" value="month" />
              </el-select>
            </div>
          </template>
          <div ref="nutritionChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 目标设置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentGoal ? '修改目标' : '设置目标'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="goalForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="目标类型" prop="type">
          <el-radio-group v-model="goalForm.type">
            <el-radio-button value="lose_weight">减重</el-radio-button>
            <el-radio-button value="maintain">保持体重</el-radio-button>
            <el-radio-button value="gain_muscle">增肌</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="当前体重" prop="currentWeight">
          <el-input-number
            v-model="goalForm.currentWeight"
            :min="30"
            :max="200"
            :precision="1"
            :step="0.1"
          >
            <template #append>kg</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="目标体重" prop="targetWeight">
          <el-input-number
            v-model="goalForm.targetWeight"
            :min="30"
            :max="200"
            :precision="1"
            :step="0.1"
          >
            <template #append>kg</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="每周目标" prop="weeklyGoal">
          <el-select v-model="goalForm.weeklyGoal" style="width: 100%">
            <el-option label="减重0.25kg" value="0.25" />
            <el-option label="减重0.5kg" value="0.5" />
            <el-option label="减重0.75kg" value="0.75" />
            <el-option label="减重1kg" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标日期" prop="targetDate">
          <el-date-picker
            v-model="goalForm.targetDate"
            type="date"
            placeholder="选择目标日期"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="活动水平" prop="activityLevel">
          <el-select v-model="goalForm.activityLevel" style="width: 100%">
            <el-option label="久坐不动" value="sedentary" />
            <el-option label="轻度活动" value="lightly_active" />
            <el-option label="中度活动" value="moderately_active" />
            <el-option label="重度活动" value="very_active" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { formatDate } from '@/utils/date'

const store = useStore()
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const weightChartRef = ref(null)
const nutritionChartRef = ref(null)
let weightChart = null
let nutritionChart = null

// 图表范围选择
const weightChartRange = ref('week')
const nutritionChartRange = ref('week')

// 当前目标
const currentGoal = ref(null)

// 目标表单
const goalForm = reactive({
  type: 'lose_weight',
  currentWeight: null,
  targetWeight: null,
  weeklyGoal: '0.5',
  targetDate: null,
  activityLevel: 'moderately_active'
})

// 表单验证规则
const rules = {
  type: [
    { required: true, message: '请选择目标类型', trigger: 'change' }
  ],
  currentWeight: [
    { required: true, message: '请输入当前体重', trigger: 'blur' }
  ],
  targetWeight: [
    { required: true, message: '请输入目标体重', trigger: 'blur' }
  ],
  weeklyGoal: [
    { required: true, message: '请选择每周目标', trigger: 'change' }
  ],
  targetDate: [
    { required: true, message: '请选择目标日期', trigger: 'change' }
  ],
  activityLevel: [
    { required: true, message: '请选择活动水平', trigger: 'change' }
  ]
}

// 目标进度
const goalProgress = computed(() => {
  if (!currentGoal.value) return 0
  const totalDays = (new Date(currentGoal.value.targetDate) - new Date(currentGoal.value.startDate)) / (1000 * 60 * 60 * 24)
  const passedDays = (new Date() - new Date(currentGoal.value.startDate)) / (1000 * 60 * 60 * 24)
  return Math.min(Math.round((passedDays / totalDays) * 100), 100)
})

// 显示目标设置表单
const showGoalForm = () => {
  if (currentGoal.value) {
    Object.assign(goalForm, currentGoal.value)
  }
  dialogVisible.value = true
}

// 提交目标
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true
        if (currentGoal.value) {
          await store.dispatch('goals/updateGoal', {
            goalId: currentGoal.value.id,
            data: goalForm
          })
        } else {
          await store.dispatch('goals/setGoal', goalForm)
        }
        ElMessage.success('目标设置成功')
        dialogVisible.value = false
        await fetchCurrentGoal()
      } catch (error) {
        console.error('设置目标失败:', error)
        ElMessage.error('设置失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 获取目标类型文本
const getGoalText = (type) => {
  const texts = {
    lose_weight: '减重',
    maintain: '保持体重',
    gain_muscle: '增肌'
  }
  return texts[type] || type
}

// 获取目标类型标签样式
const getGoalType = (type) => {
  const types = {
    lose_weight: 'danger',
    maintain: 'warning',
    gain_muscle: 'success'
  }
  return types[type] || 'info'
}

// 获取每周目标文本
const getWeeklyGoalText = (goal) => {
  return `每周${goal}kg`
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() <= Date.now()
}

// 获取当前目标
const fetchCurrentGoal = async () => {
  try {
    await store.dispatch('goals/getGoal')
    currentGoal.value = store.state.goals.currentGoal
  } catch (error) {
    console.error('获取目标失败:', error)
    ElMessage.error('获取目标失败')
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    // 获取体重记录
    await store.dispatch('goals/getWeightRecords', {
      range: weightChartRange.value
    })
    
    // 获取营养达标率
    await store.dispatch('goals/getNutritionAchievement', {
      range: nutritionChartRange.value
    })
    
    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  const isDark = document.documentElement.getAttribute('data-theme') === 'dark'
  const textColor = isDark ? '#909399' : '#303133'
  const axisLineColor = isDark ? '#4C4D4F' : '#E4E7ED'

  const theme = {
    textStyle: {
      color: textColor
    },
    axisLine: {
      lineStyle: {
        color: axisLineColor
      }
    }
  }

  // 体重变化趋势图
  weightChart = echarts.init(weightChartRef.value)
  const weightOption = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const date = params[0].axisValue
        let result = `${date}<br/>`
        params.forEach(param => {
          result += `${param.seriesName}: ${param.value}kg<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['实际体重', '目标体重'],
      textStyle: theme.textStyle
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: theme.axisLine,
      axisLabel: {
        ...theme.textStyle,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '体重(kg)',
      axisLine: theme.axisLine,
      axisLabel: {
        ...theme.textStyle,
        formatter: '{value}kg'
      }
    },
    series: [
      {
        name: '实际体重',
        type: 'line',
        data: [],
        smooth: true,
        symbolSize: 8,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.3)' },
            { offset: 1, color: 'rgba(64,158,255,0.1)' }
          ])
        }
      },
      {
        name: '目标体重',
        type: 'line',
        data: [],
        smooth: true,
        symbolSize: 8,
        lineStyle: {
          type: 'dashed'
        },
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  weightChart.setOption(weightOption)

  // 营养摄入达标率图
  nutritionChart = echarts.init(nutritionChartRef.value)
  const nutritionOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const date = params[0].axisValue
        let result = `${date}<br/>`
        params.forEach(param => {
          result += `${param.seriesName}: ${param.value}%<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['热量', '蛋白质', '碳水化合物'],
      textStyle: theme.textStyle
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLine: theme.axisLine,
      axisLabel: {
        ...theme.textStyle,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '达标率(%)',
      max: 100,
      axisLine: theme.axisLine,
      axisLabel: {
        ...theme.textStyle,
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '热量',
        type: 'bar',
        data: [],
        barMaxWidth: 30,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#a0cfff' }
          ])
        }
      },
      {
        name: '蛋白质',
        type: 'bar',
        data: [],
        barMaxWidth: 30,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#b3e19d' }
          ])
        }
      },
      {
        name: '碳水化合物',
        type: 'bar',
        data: [],
        barMaxWidth: 30,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#E6A23C' },
            { offset: 1, color: '#f3d19e' }
          ])
        }
      }
    ]
  }
  nutritionChart.setOption(nutritionOption)
}

// 更新图表
const updateCharts = () => {
  const loading = {
    text: '加载中...',
    textColor: document.documentElement.getAttribute('data-theme') === 'dark' ? '#909399' : '#303133',
    maskColor: 'rgba(255, 255, 255, 0.3)'
  }

  if (weightChart) {
    if (store.state.goals.weightRecords.length) {
      const records = store.state.goals.weightRecords
      weightChart.setOption({
        xAxis: {
          data: records.map(r => formatDate(r.date))
        },
        series: [
          {
            name: '实际体重',
            data: records.map(r => r.weight)
          },
          {
            name: '目标体重',
            data: records.map(r => r.targetWeight)
          }
        ]
      })
    } else {
      weightChart.showLoading(loading)
    }
  }

  if (nutritionChart) {
    if (store.state.goals.nutritionAchievement) {
      const achievement = store.state.goals.nutritionAchievement
      nutritionChart.setOption({
        xAxis: {
          data: achievement.dates
        },
        series: [
          {
            name: '热量',
            data: achievement.calories
          },
          {
            name: '蛋白质',
            data: achievement.protein
          },
          {
            name: '碳水化合物',
            data: achievement.carbs
          }
        ]
      })
    } else {
      nutritionChart.showLoading(loading)
    }
  }
}

// 监听窗口大小变化
const handleResize = () => {
  weightChart?.resize()
  nutritionChart?.resize()
}

// 添加图表范围变化监听
watch([weightChartRange, nutritionChartRange], () => {
  fetchChartData()
})

// 修改图表主题更新方法
const updateChartsTheme = () => {
  const isDark = document.documentElement.getAttribute('data-theme') === 'dark'
  const textColor = isDark ? '#909399' : '#303133'
  const axisLineColor = isDark ? '#4C4D4F' : '#E4E7ED'

  const theme = {
    textStyle: {
      color: textColor
    },
    axisLine: {
      lineStyle: {
        color: axisLineColor
      }
    }
  }

  if (weightChart) {
    weightChart.setOption({
      legend: { textStyle: theme.textStyle },
      xAxis: { 
        axisLine: theme.axisLine,
        axisLabel: { ...theme.textStyle }
      },
      yAxis: { 
        axisLine: theme.axisLine,
        axisLabel: { ...theme.textStyle }
      }
    })
  }

  if (nutritionChart) {
    nutritionChart.setOption({
      legend: { textStyle: theme.textStyle },
      xAxis: { 
        axisLine: theme.axisLine,
        axisLabel: { ...theme.textStyle }
      },
      yAxis: { 
        axisLine: theme.axisLine,
        axisLabel: { ...theme.textStyle }
      }
    })
  }
}

// 监听主题变化
watch(() => store.state.user.theme, () => {
  nextTick(() => {
    updateChartsTheme()
  })
})

onMounted(async () => {
  await fetchCurrentGoal()
  initCharts()
  await fetchChartData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  weightChart?.dispose()
  nutritionChart?.dispose()
})
</script>

<style lang="scss" scoped>
.goals-container {
  padding: 20px;

  .current-goal-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .goal-overview {
      .goal-type {
        text-align: center;
        margin-bottom: 20px;
      }

      .goal-progress {
        margin-top: 20px;

        h4 {
          margin: 0 0 12px;
          font-size: 16px;
        }

        .progress-label {
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 400px;
    }
  }
}
</style> 